#include <LiquidCrystal_I2C.h>
#include<KEYBOARD.h>
#include<Tools.h>
LiquidCrystal_I2C lcd(0x27,16,4); // 此处0x27改成刚才检测到的地址即可。
void initLCD()
{
  lcd.init();  // initialize the lcd 
  lcd.backlight();
  lcd.setCursor(0, 0); 
}
calcuator mcalc;
char key;
int times=0;
char p[25]={'0'};
double result=0;
bool flag1=false;
bool flag2=false;
bool flag3=false;
void setup()
{
  initLCD();
}
double ReadNum()
{
  int i=1;
  double result=0;
  int flag=0;
  while(key!='=')
  {
    key=input();
    if(key>='0'&&key<='9')
    {
      if(flag!=0)
      result=10*result+(key-'0');
      else
      {
        result+=(key-'0')/pow(10,i);
        i++;
      }
    }
    else if(key=='.') flag=0;
  }
  return result;
}
void ReadExp()
{
  do{
    key=input();
    lcd.print(key);
    p[times]=key;
    ++times;
    if(key=='x')
    flag1=true;
    else if(key=='y')
    flag2=true;
    else if(key=='z');
    flag3=true;
  }while(key!='=');
}

void IntegralCaculation()
{
  double in=0;
  double out=0;
  double result=0;
  lcd.print("Up:");
  lcd.setCursor(0,1);
  in=ReadNum();
  lcd.print(in);
  lcd.clear();
  lcd.print("Down");
  lcd.setCursor(0,1);
  out=ReadNum();
  lcd.print(out);
  lcd.clear();
  lcd.print("Expression:");
  lcd.setCursor(0,1);
  ReadExp();
  mcalc.change(p,times);
  result=mcalc.Romberg(out,in);
  lcd.print("Result");
  lcd.setCursor(0,1);
  lcd.print(result);
  times=0;
}
void FormulaCaculation()
{
  double result=0;
  double x;
  double y;
  double z;
    lcd.print("Expression:");
    lcd.setCursor(0,1);
    ReadExp();
    lcd.clear();
    if(flag1)
    {
      lcd.print("x:");
      lcd.setCursor(0,1);
      x=ReadNum();
      lcd.clear();
    }
    if(flag2)
    {
      lcd.print("y:");
      lcd.setCursor(0,1);
      y=ReadNum();
      lcd.clear();
    }
    if(flag3)
    {
      lcd.print("z:");
      lcd.setCursor(0,1);
      z=ReadNum();
      lcd.clear();
    }
    mcalc.change(p,times);
    result=mcalc.function(x);
    lcd.print("Result:");
    lcd.setCursor(0,1);
    lcd.print(result);
    times=0;
}
double ArithmeticOperation()
{
  char*string;
  
  lcd.print("input:");
  string=read_string();

  calc cc(string);
  lcd.print(cc.result());  
}

void loop(){
  lcd.print("please choose mode");
  lcd.setCursor(0,1);
  key=input();
  lcd.print(key);
  switch(key){
    case '1':lcd.clear(); IntegralCaculation();break;
    case '2':lcd.clear(); ArithmeticOperation();break;
    case '3':lcd.clear(); FormulaCaculation();break;
    //case '4':lcd.clear(); ProblemSetting();break;
    default: lcd.clear(); lcd.print("mode error")break;
  }
  lcd.clear();
}
